//
//  Timers.m
//  GCD定时器
//
//  Created by 崔博 on 2018/9/11.
//  Copyright © 2018年 崔博. All rights reserved.
//

#import "Timers.h"

@interface Timers()

@end

static NSMutableDictionary *timers;
@implementation Timers
+ (void)initialize
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        timers = [NSMutableDictionary dictionary];
    });
}
+ (NSString *)execTask:(void (^)(void))task
           start:(NSTimeInterval)start
        interval:(NSTimeInterval)interval
         repeats:(BOOL)repeats async:(BOOL)async
{
    if (!task || start < 0 || (interval <= 0 && repeats)) return nil;
    static int i = 0;
    // 定时器唯一标示
    NSString * name = [NSString stringWithFormat:@"%d",i++];
    dispatch_queue_t queue = async ? dispatch_queue_create("timer", DISPATCH_QUEUE_SERIAL) : dispatch_get_main_queue();
    
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 1 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(timer, ^{
        task();
        if (!repeats) {
            [self cancel:name];
        }
    });
    dispatch_resume(timer);
    timers[name] = timer;
    return name;
}
+ (void)cancel:(NSString *)cancel
{
    if (!cancel.length) {
        return ;
    }
    dispatch_source_t timer =  timers[cancel];
    if (timer == nil) {
        NSAssert(timer==nil, @"没有找到定时器");
    }
    dispatch_source_cancel(timer);
    [timers removeObjectForKey:cancel];
}
@end
